package chapter14;

import java.sql.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-03-26 上午10:09
 */
public class PrepareStatementTest {
    public static void main(String[] args) {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://192.168.100.66/java_test?useSSL=false&serverTimezone=UTC&amp";
        String userName = "root";
        String password = "crscd123@";

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }

        try (Connection conn = DriverManager.getConnection(url, userName, password)
        ) {
            System.out.println(conn);

            String sql_insert = "INSERT INTO book (name, price, pubdate) VALUES (?,?,?);";
            PreparedStatement statement = conn.prepareStatement(sql_insert);
            statement.setString(1, "test3");
            statement.setDouble(2, 343.34);
            statement.setDate(3, new Date(new java.util.Date().getTime()));
            int len = statement.executeUpdate();
            System.out.println("insert into db:" + len);

            String sql_query = "SELECT * FROM book";
            ResultSet rs = statement.executeQuery(sql_query);
            while (rs.next()) {
                long id = rs.getInt("id");
                String name = rs.getString("name");
                double price = rs.getDouble("price");
                java.util.Date date = new java.util.Date(rs.getDate("pubdate").getTime());
                System.out.println(String.format("id:%d,name:%s,price:%5.2f, pub date:%s", id, name, price, date.toString()));
            }

            String sql_count = "SELECT COUNT(id) FROM book";
            PreparedStatement statement1 = conn.prepareStatement(sql_count);
            ResultSet rs1 = statement1.executeQuery();
            while (rs1.next()) {
                int count = rs1.getInt(1);
                System.out.println("book num:" + count);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
